import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { EditService } from "./edit.service";
import { InvestService } from "../../invest.service";
import { RemindComponent } from "../remind/remind.component";
import * as _ from 'lodash';
import { Util } from 'app/common/util';
import { TableComponent } from "../../modal/table/table.component";

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
  providers: [EditService]
})
export class EditComponent implements OnInit {
  // 提醒者模版
  @ViewChild("editRemind", { read: ViewContainerRef })
  editRemind: ViewContainerRef;
  remindComponent: ComponentRef<RemindComponent>;
  // 模版
  @ViewChild("editTable", { read: ViewContainerRef })
  editTable: ViewContainerRef;
  editTableComponent: ComponentRef<TableComponent>;
  // 列表新数据
  public dataList: any = [];
  // 克隆列表新数据,用于页面数据标红对比
  public isChangeList: any = [];
  // 用于是否显示下拉框
  public isEditList: any = [];
  // 克隆对象,用于对比
  public cloneList: any = [];
  // 提醒信息
  public auditOprZh: any;
  public remindBody: any = {
    auditOpr: '',
    title: '',
    content: ''
  };
  //短信提醒
  public sSMSFlag: any = false;
  //邮件提醒
  public sEmailFlag: any = false;
  // 字典值
  public dictionaryList: any = {
    ID_FIELD_TYPE: []
  };

  constructor(
    public editService: EditService,
    public resolver: ComponentFactoryResolver,
    public investService: InvestService
  ) { }

  ngOnInit() {
    // 加载table
    this.showEditTable();
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    // 克隆对象，用于对比
    this.cloneList = _.cloneDeep(this.dataList);
    this.defaultValue();
  }
  ngAfterViewInit() {
    let that = this;
    // 用于接收提醒者数据
    this.investService.remindData = new EventEmitter();
    this.investService.remindData.subscribe((data: any) => {
      if (data) {
        that.remindBody.auditOpr = _.cloneDeep(data.userChecked);
        that.auditOprZh = _.cloneDeep(data.displayName);
      }
    })
  }
  // 保存/保存并提交
  saveOrSubmit(type: any) {
    let that = this;
    let checkedItem = [];
    if (Util.objectCheck(this.editTableComponent.instance.dataList[0], this.cloneList[0])) {
      window['swal']("提示", this.editTableComponent.instance.dataList[0].sFullName + " 信息没有修改", "warning");
    } else {
      // 防止删除其他操作有用属性，另起变量赋值
      let it = _.cloneDeep(this.editTableComponent.instance.dataList[0]);
      // 产品内码赋值给nIxId，假设是新增，后台需要这个字段进行关联
      it.nIxId = it.nFundNo;
      delete it.sFundType;
      delete it.sFundCode;
      delete it.sFullName;
      delete it.sStatus;
      delete it.changeInitiator;
      delete it.changeDate;
      delete it.reviewer;
      delete it.auditDate;
      delete it.sOprStateZh;
      delete it.sStep;
      delete it.isChecked;
      delete it.nFundNo;
      delete it.riskAuditOpr;
      delete it.riskAuditDate;
      delete it.sStepZh;
      delete it.sFundTypeZh;
      delete it.sFlowStepZh;
      delete it.sOprZh;
      checkedItem.push(it);
      switch (type) {
        case 'save':
          window['swal']({
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            showLoaderOnConfirm: true,
            title: "提示",
            text: "是否确认保存?",
            html: true
          }, function (isConfirm) {
            if (isConfirm) {
              that.editService.save(checkedItem).subscribe(data => {
                if (data) {
                  window['$']('#edit').modal('hide');
                  window['swal']("成功", "保存成功", "success");
                  that.investService.targetEdit.emit('refresh');
                }
              })
            }
          })
          break;
        case 'saveSubmits':
          window['swal']({
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            showLoaderOnConfirm: true,
            title: "提示",
            text: "是否确认保存并提交?",
            html: true
          }, function (isConfirm) {
            if (isConfirm) {
              let postBody: any = {
                auditContentBean: that.remindBody,
                pmsInvestJournal: checkedItem
              }
              that.editService.saveSubmits(postBody).subscribe(data => {
                if (data) {
                  window['$']('#edit').modal('hide');
                  window['swal']("成功", "保存成功", "success");
                  that.investService.targetEdit.emit('refresh');
                }
              })
            }
          })
          break;
      }
    }
  }
  // 接收者列表
  showRemind() {
    if (this.remindComponent && this.remindComponent.instance) {
      this.remindComponent.destroy();
    }
    const remindComponent = this.resolver.resolveComponentFactory(RemindComponent);
    this.remindComponent = this.editRemind.createComponent(remindComponent);
    window['$']('#editRemind').modal('show');
  }

  //获取默认模板接口
  defaultValue() {
    let that = this;
    let getBody: any = {
      "sButtonId": '70132@invest_scope_data_btn_i_commit'
    }
    this.editService.defaultValue(getBody).subscribe(data => {
      if (data) {
        if (Array.isArray(data)) {
          if (data.length > 1) {
            that.auditOprZh = data[0].sContentZh;
            that.remindBody.auditOpr = data[0].sContent;
            if (data[0].sSMSFlag == 'true') {
              that.sSMSFlag = true;
            }
            if (data[0].sEmailFlag == 'true') {
              that.sEmailFlag = true;
            }
            that.remindBody.content = data[1].sContent;
            that.remindBody.title = data[1].sRemindTitle;
          }
        }
      }
    })
  }
  //设置默认接口
  setDefault() {
    let that = this;
    let postBody = _.cloneDeep(this.remindBody);
    postBody['sButtonId'] = '70132@invest_scope_data_btn_i_commit';
    postBody['sEmailFlag'] = _.cloneDeep(this.sEmailFlag);
    postBody['sEmailContent'] = _.cloneDeep(postBody.content);
    postBody['sSMSFlag'] = _.cloneDeep(this.sSMSFlag);
    postBody['sSMSContent'] = _.cloneDeep(postBody.content);
    delete postBody.content;
    if (postBody.sEmailFlag) {
      postBody.sEmailFlag = 'Y'
    } else {
      postBody.sEmailFlag = 'N'
    }
    if (postBody.sSMSFlag) {
      postBody.sSMSFlag = 'Y'
    } else {
      postBody.sSMSFlag = 'N'
    }
    console.log(postBody)
    window['swal']({
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      showLoaderOnConfirm: true,
      title: "提示",
      text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否设置默认" + "</div>",
      html: true
    },
      function (isConfirm) {
        if (isConfirm) {
          that.editService.setDefault(postBody).subscribe(data => {
            if (data) {
              window['swal']("提示", "设置默认成功", "success");
            }

          })
        }
      });
  }
  // 模版
  showEditTable() {
    let that = this;
    if (this.editTableComponent && this.editTableComponent.instance) {
      this.editTableComponent.destroy();
    }
    new Promise((resolve, reject) => {
      const editTableComponent = that.resolver.resolveComponentFactory(TableComponent);
      that.editTableComponent = that.editTable.createComponent(editTableComponent);
      that.editTableComponent.instance.isEdit = 'yes';
      that.editTableComponent.instance.isShowCol1 = 'sFundTypeZh';
      that.editTableComponent.instance.isShowCol2 = 'sFullName';
      that.editTableComponent.instance.isShowCol3 = 'sStepZh';
      // 用于标红对比
      that.isChangeList = _.cloneDeep(that.dataList);
      // 用于是否显示下拉框
      that.isEditList = _.cloneDeep(that.dataList);
      _.forEach(that.isChangeList, item => {
        // 将所有赋false,修改页面不需要标红
        _.forIn(item, (value, key) => {
          item[key] = false;
        })
      })
      _.forEach(that.isEditList, item => {
        // 将所有赋'no',修改页面不需要显示下拉框
        _.forIn(item, (value, key) => {
          item[key] = 'no';
        })
      })
      resolve(resolve);
    }).then(resolve => {
      that.editTableComponent.instance.dataList = _.cloneDeep(that.dataList);
      that.editTableComponent.instance.isChangeList = _.cloneDeep(that.isChangeList);
      that.editTableComponent.instance.isEditList = _.cloneDeep(that.isEditList);
    })
  }
}
